<%@ page language="java" contentType="text/html; charset=utf8"
	pageEncoding="utf8"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf8">
	<link type="text/css" href="resources/css/main.css" rel="stylesheet" />
    <style>
    #toolbar {
        padding: 10px 4px;
    }
    
    #jqUserOrderList {
        font-size: 20px;
    }
    
    </style>	
<script type="text/javascript">
function submitOrder(orderId){
 		//alert('submit=' + orderId);
 		  $.ajax({
	          url : 'json/entity/userOrder/submit',
	          type: 'POST',
	          dataType : "json",
	          data : {
	        	  id : orderId
	          		},
	          success : function(data) {
	        	  $("#jqUserOrderList").trigger("reloadGrid");
	          		},
	          error: function() {
	         	            alert('Error occured');
	         	        }   	          		
      	});
 		
 		
 	};

 	
function download(orderId) {
	var type = "DOCX";
	// Retrieve download token
	// When token is received, proceed with download
	$.get('reports/download/token', function(response) {
		// Store token
		var token = response.message[0];
		
		// Show progress dialog
		$('#msgbox').text('Формирование заказа...');
		$('#msgbox').dialog( 
				{	title: 'Загрузка',
					modal: true,
					buttons: {"Закрыть": function()  {
						$(this).dialog("close");} 
					}
				});
		 
		// Start download 
		window.location = 'reports/download/report'+'?token='+token+'&type='+type+'&orderId='+orderId;
		//window.open = ('reports/download/report'+'?token='+token+'&type='+type);
		// Check periodically if download has started
		var frequency = 1000;
		var timer = setInterval(function() {
			$.get('reports/download/progress', {token: token}, 
					function(response) {
						// If token is not returned, download has started
						// Close progress dialog if started
						if (response.message[0] != token) {
							$('#msgbox').dialog('close');
							clearInterval(timer);
						}
				});
		}, frequency);
		
	});
}; 	
 	
var lastSel = "";
$(function(){ 
	
	/* ------------------ GRID FUNCTION ----------------- */	
  $("#jqUserOrderList").jqGrid({
	jsonReader : {
	      root:"rows",
	      page: "page",
	      total: "total",
	      records: "records",
	      repeatitems: false,
	      id: "0"
	   },	  
    url:'json/entity/userOrder',
    datatype: 'json',
    mtype: 'GET',
    colNames:['№','','Номер заказа', 'Дата заказа', 'Отправить','Статус заказа',''],
    colModel :[ 
      {name:'id', 			index:'id', 					width:10, sortable:false },
      {name:'id', 			index:'id', 					width:15, sortable:false,
    	  formatter: printButtonFormatter},
      {name:'orderNr',		index:'orderNr', 				width:40, sortable:false },   
      {name:'orderDate',	index:'orderDate', 				width:40, sortable:false },
      {name:'id', 			index:'id', 					width:90, align:'center', 
    	  fixed:true, sortable:false, resize:false, formatter: submitFormatter},
      {name:'orderStatus',	index:'orderStatus', 			width:40, sortable:false, formatter: statusFormatter },
      {name:'id', 			index:'id', 					width:60, align:'center', 
				    	  fixed:true, sortable:false, resize:false, 
				    	  formatter:'actions', formatoptions:{keys:true,editbutton: false}}
    ],
    pager: '#pager',
    toppager: false,
    rowNum:10,
    rowList:[10,20,30],
    sortname: 'id',
    sortorder: 'asc',
    viewrecords: true,
    gridview: true,
    autowidth: true,
    height: 'auto',
    caption: 'Ваши заказы',
    search: true,
    editurl : 'json/entity/userOrder/edit',
	    subGrid: true,
		caption: "Список ваших заказов",
		// define the icons in subgrid
		subGridOptions: {
			"plusicon"  : "ui-icon-triangle-1-e",
			"minusicon" : "ui-icon-triangle-1-s",
			"openicon"  : "ui-icon-arrowreturn-1-e"
		},
		subGridRowExpanded: function(subgrid_id, row_id) {
			var subgrid_table_id, pager_id;
			subgrid_table_id = subgrid_id+"_t";
			pager_id = "p_"+subgrid_table_id;
			$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll' style=' font-size: 16px;'></table>");
			jQuery("#"+subgrid_table_id).jqGrid({
				jsonReader : {
				      root:"rows",
				      page: "page",
				      total: "total",
				      records: "records",
				      repeatitems: false,
				      id: "0"
				   },
				url:'json/entity/userOrderDetail?orderId=' + row_id,
				datatype: 'json',
				colNames: ['#','Inventar Nr','Photo','Begin', 'End', 'Reservation'],
				colModel: [
					{name:'id',index:'id',width:80,key:true, sortable:false },
					{name:'advertisingRegistry.inventarNr', 	   	index:'advertisingRegistry.inventarNr', 	width:100, sortable:false },
					{name:'photo', 				index:'photo',				width:120, formatter: photoFormatter, sortable:false },      
					{name:'beginCommandDate',index:'beginCommandDate'	,width:120, sortable:false },
					{name:'endCommandDate',index:'endCommandDate'		,width:120, sortable:false },
					{name:'reservationType',index:'reservationType'		,width:180, sortable:false, formatter: reservationFormatter }
				],
			   	rowNum:20,
			   	sortname: 'num',
			    sortorder: 'asc',
			    height: '100%'
			});
		}
	
	
  }); 
	
  function printButtonFormatter(cellvalue, options, rowObject) {
	return  "<input type='button'  value='Печать' onclick=\"download('"+rowObject['id']+"');\" />"; 
  }	
	
  function submitFormatter(cellvalue, options, rowObject) {
	  if (rowObject['orderStatus'] == 0 ){
		  var buName = "bt_"+rowObject['id'];
		  var ret ="<input type='button'  value='Отправить' onclick=\"submitOrder('"+rowObject['id']+"');\" />";
		  return ret;
	  } else {
		  return "";
	  }
	}; 
	
	function photoFormatter(cellvalue, options, rowObject) {
		return "<img src='images/small/" + (rowObject['advertisingRegistry'])['inventarNr'] + "' width='120' alt='Photo' title='PHOTO' />";
	}; 
	
	function statusFormatter(cellvalue, options, rowObject) {
		if (cellvalue==0) return "Проект"; 
		if (cellvalue==1) return "Отправлено";
		if (cellvalue==2) return "Утверждено";
		if (cellvalue==3) return "Отклонено";
	};	
	
	function reservationFormatter(cellvalue, options, rowObject) {
		if (cellvalue==0) return "Свободно"; 
		if (cellvalue==1) return "Зарезервировано";
		if (cellvalue==2) return "Продано по договору";
	};	
	
	function photoFormatter(cellvalue, options, rowObject) {
		return "<img src='images/small/" + (rowObject['advertisingRegistry'])['inventarNr'] + "' width='120' alt='Photo' title='PHOTO' />";
	};   

	function priceFormatter(cellvalue, options, rowObject) {
  		return cellvalue + " \u20AC";
	};   

	
});
	
</script>	
	<title>Insert title here</title>
</head>
<body>

<!-- <span id="toolbar" class="ui-widget-header ui-corner-all"> -->
<!--     <button id="placeOrder" disabled="disabled">Place Order</button> -->
<!-- </span> -->
<!-- 	<div id="checkResult"></div> -->
<table id="jqUserOrderList">
	<tr><td/></tr>
</table>
<div id='msgbox' title='' style='display:none'></div>
</body>
</html>
